/**
 * 
 */
package qy.jalgotrade.barfeed.resampled;

import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;

import qy.jalgotrade.bar.Bar;
import qy.jalgotrade.bar.Bars;
import qy.jalgotrade.dataseries.resampled.BarGrouper;
import qy.jalgotrade.utils.resamplebase.Grouper;

/**
 * 与汇总单品种 Bar 的 pyalgotrade.dataseries.resampled.BarGrouper 类似, 汇总一组 Bars (pyalgotrade.bar.Bars):
 * 
 * @author qy
 *
 */
public class BarsGrouper extends Grouper<Bars> {

	private Map<String, Grouper<Bar>> __barGroupers;

	private Bar.Frequency __frequency;

	/**
	 * 
	 * @param groupDateTime
	 * @param bars
	 * @param frequency
	 */
	public BarsGrouper(ZonedDateTime groupDateTime, Bars bars, Bar.Frequency frequency) {

		super(groupDateTime);
		__barGroupers = new HashMap<>();
		__frequency = frequency;

		// Initialize BarGrouper instances for each instrument.
		for (String instrument : bars.keys()) {
			Bar bar = bars.getBar(instrument);
			Grouper<Bar> barGrouper = new BarGrouper(groupDateTime, bar, frequency);
			__barGroupers.put(instrument, barGrouper);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see qy.jalgotrade.utils.resamplebase.Grouper#addValue(java.lang.Object)
	 */
	@Override
	public void addValue(Bars value) {

		// Update or initialize BarGrouper instances for each instrument.
		for (String instrument : value.keys()) {
			Bar bar = value.getBar(instrument);
			Grouper<Bar> barGrouper = __barGroupers.get(instrument);
			if (barGrouper != null) {
				barGrouper.addValue(bar);
			} else {
				barGrouper = new BarGrouper(getDateTime(), bar, __frequency);
				__barGroupers.put(instrument, barGrouper);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * @see qy.jalgotrade.utils.resamplebase.Grouper#getGrouped()
	 */
	@Override
	public Bars getGrouped() throws Exception {

		Map<String, Bar> barDict = new HashMap<>();
		for (Map.Entry<String, Grouper<Bar>> e : __barGroupers.entrySet()) {
			String instrument = e.getKey();
			Grouper<Bar> grouper = e.getValue();
			barDict.put(instrument, grouper.getGrouped());
		}
		return new Bars(barDict);
	}
}
